// Package api @Title api[简述该包的主要作用]
// @Description
// @Author  cnHuaShao
// @since v0.0.1
// @Version v1.0.0
// @Date 2024/5/1 23:32
// @Update 2024/5/1 23:32
package api

import (
	"FinancialManagement/src/base/mess"
	"FinancialManagement/src/base/util"
	"FinancialManagement/src/business/inventory"
	"database/sql"
	"github.com/gin-gonic/gin"
	"gopkg.in/guregu/null.v3"
	"net/http"
	"time"
)

// GetInventoryTypeList
// @Description: 获取所有库存类型列表，可模糊搜索
// @param c
func GetInventoryTypeList(c *gin.Context) {
	typeName := c.DefaultPostForm("typeName", "") // 查询条件
	inventoryTypes, err := inventory.GetAllInventoryTypes(typeName)
	if err != nil {
		c.JSON(http.StatusOK, mess.ResErrMess(910005002, err.Error()))
		return
	}
	c.JSON(http.StatusOK, mess.ResMessOK(inventoryTypes))
}

// DelInventoryType
// @Description: 删除指定库存类型
// @param c
func DelInventoryType(c *gin.Context) {
	typeId := util.ToInt(c.DefaultPostForm("typeId", "0")) // 要删除的类型ID
	if typeId == 0 {
		c.JSON(http.StatusOK, mess.ResErrMess(910005001, "请求参数不能为空"))
		return
	}
	if err := inventory.DelInventoryType(typeId); err != nil {
		c.JSON(http.StatusOK, mess.ResErrMess(910005003, err.Error()))
		return
	}
	c.JSON(http.StatusOK, mess.ResMessOK(nil))
}

// CreateInventoryType
// @Description: 创建库存类型
// @param c
func CreateInventoryType(c *gin.Context) {
	typeName := c.DefaultPostForm("typeName", "")                      // 库存类型名称
	typeDescription := c.DefaultPostForm("typeDescription", "")        // 库类型描述
	parentTypeId := util.ToInt(c.DefaultPostForm("parentTypeId", "0")) // 所属父级编号
	unit := c.DefaultPostForm("unit", "")                              // 类型使用单位
	if typeName == "" || unit == "" {
		c.JSON(http.StatusOK, mess.ResErrMess(910005001, "请求参数不能为空"))
		return
	}
	if err := inventory.CreateInventoryType(inventory.InventoryType{
		TypeName: typeName,
		TypeDescription: null.String{sql.NullString{
			String: typeDescription,
			Valid:  typeDescription != "",
		}},
		ParentTypeID: parentTypeId,
		Unit: null.String{sql.NullString{
			String: unit,
			Valid:  unit != "",
		}},
		CreatedAt: time.Now().Unix(),
	}); err != nil {
		c.JSON(http.StatusOK, mess.ResErrMess(910005004, err.Error()))
		return
	} else {
		c.JSON(http.StatusOK, mess.ResMessOK(nil))
		return
	}
}
